package com.mechat.view

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.LinearLayout
import com.custom.base.util.SDViewUtil
import com.mechat.R
import com.mechat.bean.ConversationChatListBean
import com.mechat.bean.ModelListBean
import com.mechat.util.GlideUtil
import io.rong.imkit.utils.GlideUtils
import io.rong.imkit.widget.refresh.util.DesignUtil
import kotlinx.android.synthetic.main.select_view_select.view.viewSelectLl
import kotlinx.android.synthetic.main.select_view_select_tv.view.viewSelectTv
import kotlinx.android.synthetic.main.select_view_select_tv.view.viewSelectView
import kotlinx.android.synthetic.main.select_view_select_tv.view.avatar_select
import kotlinx.android.synthetic.main.select_view_select_tv.view.txt_chats_unread_size

/**
 * 说明：选择控件
 */
class SelectView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
    private var clickListener: OnSelectClickListener? = null
    private var selectViewColor = 0
    private var noSelectViewColor = 0
    private var selectTvColor = 0
    private var noSelectTvColor = 0
    private var selectTvSize = 0f
    private var noSelectTvSize = 0f
    private var bold = false //是否粗体
    private var isView = true //是否显示底部view
    private var isAverage = false //是否平均分
    private var isUpdate = true //是否点击的时候更新界面
    private var index = 0 //初始位置
    private var textViews = mutableListOf<View>() //tab数据
    private var btView: View? = null
    private var lastIndex = 0
    private var animationStart = 0f
    private var animationEnd = 0f
    private var viewWidth = arrayListOf<Int>()

    init {
        val selectAttrs: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectView)
//        val texts = selectAttrs.getString(R.styleable.SelectView_SelectView_tabs).toString()
        val bgColor = selectAttrs.getColor(R.styleable.SelectView_SelectView_bgColor, Color.parseColor("#FFFFFF"))
        selectViewColor = selectAttrs.getColor(R.styleable.SelectView_SelectView_selectViewColor, Color.parseColor("#FFFFA200"))
        noSelectViewColor = selectAttrs.getColor(R.styleable.SelectView_SelectView_noSelectViewColor, Color.parseColor("#00000000"))
        selectTvColor = selectAttrs.getColor(R.styleable.SelectView_SelectView_selectTvColor, Color.parseColor("#FF1677FF"))
        noSelectTvColor = selectAttrs.getColor(R.styleable.SelectView_SelectView_noSelectTvColor, Color.parseColor("#333333"))
        selectTvSize = selectAttrs.getDimension(R.styleable.SelectView_SelectView_selectTvSize, 16f)
        noSelectTvSize = selectAttrs.getDimension(R.styleable.SelectView_SelectView_noSelectTvSize, 12f)
        bold = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_bold,false)
        isView = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isView,true)
        isAverage = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isAverage,false)
        isUpdate = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isUpdate,true)

//        if(!isView){
//            gravity = Gravity.CENTER_VERTICAL
//        }

        setBackgroundColor(bgColor)

//        if(texts!="null"){
//            upDate()
//        }
    }

    /**
     * 计算移动终点的只
     */
    private fun cha(zhi:Int = 0,i:Int = lastIndex): Float {
        var z = zhi
        z += if(i == lastIndex || i == index) viewWidth[i]/2
        else viewWidth[i]
        return when {
            i != index -> cha(z,if(index > lastIndex) i+1 else i-1)
            index > lastIndex -> animationStart+z.toFloat()
            else -> animationStart-z.toFloat()
        }
    }
    /**
     * 更新滑块位置
     */
    private fun updateSlider(){
        btView?.apply {
            if(viewWidth.size>0){
                animationStart = animationEnd
                animationEnd = cha()
                val translateAnimation: Animation = TranslateAnimation(animationStart, animationEnd, 0f, 0f) //设置平移的起点和终点
                translateAnimation.duration = 200 //动画持续的时间
                translateAnimation.isFillEnabled = true //使其可以填充效果从而不回到原地
                translateAnimation.fillAfter = true //不回到起始位置
                //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
                animation = translateAnimation //给imageView添加的动画效果
                translateAnimation.startNow() //动画开始执行 放在最后即可
                lastIndex = index
            }
        }
    }
    /**
     * 设置tab数据
     */
    fun setTabText(split: List<ModelListBean>) {
        val view = SDViewUtil.getRId(R.layout.select_view_select)

        if(isAverage) SDViewUtil.setViewWidthMatchParent(view.viewSelectLl)
        else SDViewUtil.setViewWidthWrapContent(view.viewSelectLl)
        for (i in split.indices){
            val tvView = SDViewUtil.getRId(R.layout.select_view_select_tv)
            GlideUtil.setImageView(split[i].modelAccount.avatarUrl,tvView.avatar_select, placeholderImageId = 0)
            tvView.viewSelectView.visibility=View.VISIBLE
            tvView.viewSelectTv.gravity = Gravity.CENTER
            tvView.viewSelectTv.text = split[i].modelAccount.nickName
            tvView.txt_chats_unread_size.visibility=if (split[i].modelAccount.unReadNum > 0)View.VISIBLE else View.GONE
            tvView.txt_chats_unread_size.text=if (split[i].modelAccount.unReadNum>99)"99+" else "${split[i].modelAccount.unReadNum}"
            tvView.setOnClickListener {
                if(index != i){
                    index = i
                    clickListener?.onSelect(i)
                    if(isUpdate) upDate()
                }
            }
//            if(isAverage) view.viewSelectLl.addView(tvView,LayoutParams(0,LayoutParams.MATCH_PARENT,1f))
//            else
                view.viewSelectLl.addView(tvView)
            textViews.add(tvView)
        }
        addView(view,SDViewUtil.layoutParamsLinearLayoutMW)
        upDate()
//        if(isView) SDViewUtil.getViewSize(view.viewSelectView,true,200,object :SDViewUtil.SDViewSizeListener{
//            override fun onResult(v: View) {
//                textViews.forEach {
//                    viewWidth.add(SDViewUtil.getViewWidth(it))
//                }
//                if(viewWidth.size>0) SDViewUtil.setViewMarginLeft(view.viewSelectView,viewWidth[0]/2-v.width/2)
//            }
//        })
    }

    /**
     * 开始更新UI
     */
    fun start() {
        upDate()
    }

    /**
     * 改变选中位置
     */
    fun setIndex(i:Int) {
        index = i
        upDate()
    }

    /**
     * 更新UI
     */
    private fun upDate(){
//        updateSlider()
        for (i in textViews.indices){
            val tv = textViews[i].viewSelectTv
            val bottomLine = textViews[i].viewSelectView
            if(index == i){
                tv.setTextColor(selectTvColor)
                tv.textSize = selectTvSize
                tv.typeface = Typeface.defaultFromStyle(if(bold) Typeface.BOLD else Typeface.NORMAL)
                bottomLine.visibility= View.VISIBLE
                textViews[i].avatar_select.setBackgroundResource(R.drawable.shape_stroke_white_circle)
                val layoutParams =  textViews[i].avatar_select.layoutParams
                layoutParams.width=DesignUtil.dp2px(context,66f)
                layoutParams.height=DesignUtil.dp2px(context,66f)
                textViews[i].avatar_select.layoutParams=layoutParams
            }else{
                tv.setTextColor(noSelectTvColor)
                tv.textSize = noSelectTvSize
                tv.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                bottomLine.visibility= View.GONE
                textViews[i].avatar_select.setBackgroundColor(Color.parseColor("#4699FF"))

                val layoutParams =  textViews[i].avatar_select.layoutParams
                layoutParams.width=DesignUtil.dp2px(context,58f)
                layoutParams.height=DesignUtil.dp2px(context,58f)
                textViews[i].avatar_select.layoutParams=layoutParams
            }

        }

    }

    /**
     * 设置点击事件
     */
    fun setClickListener(listener: OnSelectClickListener): SelectView {
        this.clickListener = listener
        return this
    }
    interface OnSelectClickListener {
        fun onSelect(index: Int)
    }

    /**
     * 获取数据数量
     */
    fun getDataSize(): Int {
        return textViews.size
    }

    /**
     * 获取初始位置
     */
    fun getIndex(): Int {
        return index
    }


    fun getViewWidth(): ArrayList<Int> {
        return viewWidth
    }
    fun setViewWidth(viewWidth : ArrayList<Int>){
        this.viewWidth = viewWidth
    }
}